<template>
  <div class="login">
    <el-form class="form" :model="model" :rules="rules" ref="loginForm">
      <h1 class="title">Admin后台管理系统</h1>
      <el-form-item prop="userName">
        <el-input
          class="text"
          v-model="model.userName"
          prefix-icon="User"
          clearable
          :placeholder="$t('login.username')"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="model.password"
          prefix-icon="Lock"
          show-password
          clearable
          :placeholder="$t('login.password')"
        />
      </el-form-item>

      <el-form-item prop="captcha">
        <div class="captcha">
          <el-input
            class="text"
            v-model="model.captcha"
            prefix-icon="Picture"
            placeholder="请输入验证码"
          ></el-input>
          <img
            :src="captchaSrc"
            width="200"
            height="40"
            @click="refreshCaptcha"
          />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="submit"
        >
          {{ btnText }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="change-lang">
    <ChangeLang />
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { Login, GetValidateCode } from '@/api/login'
import ChangeLang from '@/layout/components/Topbar/ChangeLang.vue'
import useLang from '@/i18n/useLang'
import { useApp } from '@/pinia/modules/app'

// 使用 Composition API
const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const loginForm = ref()
const { lang } = useLang()

// 定义响应式数据
const model = reactive({
  userName: 'admin',
  password: '123456',
  captcha: '',
  codeKey: '',
})

const loading = ref(false)
const captchaSrc = ref('')

// 表单验证规则
const rules = computed(() => ({
  userName: [
    {
      required: true,
      message: t('login.rules-username'),
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: t('login.rules-password'),
      trigger: 'blur',
    },
    {
      min: 6,
      max: 12,
      message: t('login.rules-regpassword'),
      trigger: 'blur',
    },
  ],
  captcha: [
    {
      required: true,
      message: t('login.rules-validate-code'),
      trigger: 'blur',
    },
  ],
}))

// 计算按钮文本
const btnText = computed(() =>
  loading.value ? t('login.logining') : t('login.login')
)

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const { data } = await GetValidateCode()
    model.codeKey = data.codeKey
    captchaSrc.value = data.codeValue
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

// 提交登录
const submit = () => {
  if (loading.value) return

  loginForm.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        const { code, data, message } = await Login({
          userName: model.userName,
          password: model.password,
          captcha: model.captcha,
          codeKey: model.codeKey,
        })

        if (+code === 200) {
          ElMessage.success({
            message: t('login.loginsuccess'),
            duration: 1000,
          })

          const redirect = route.query.redirect
          if (redirect) {
            const targetPath = decodeURIComponent(redirect)
            if (targetPath.startsWith('http')) {
              window.location.href = targetPath
            } else if (targetPath.startsWith('/')) {
              router.push(targetPath)
            } else {
              router.push('/')
            }
          } else {
            router.push('/')
          }

          useApp().initToken(data)
        } else {
          ElMessage.error(message)
          refreshCaptcha()
        }
      } catch (error) {
        ElMessage.error('登录请求失败')
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    }
  })
}

// 监听语言变化
watch(lang, () => {
  // 触发重新计算 rules
  rules.value
})

// 组件挂载时刷新验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style lang="scss" scoped>
.login {
  transition: transform 1s;
  transform: scale(1);
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #2d3a4b;

  .form {
    width: 520px;
    max-width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 160px auto 0;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
      background: rgba(0, 0, 0, 0.1);
    }

    :deep(.el-input-group--append > .el-input__wrapper) {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }

    :deep(.el-input-group--prepend > .el-input__wrapper) {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }

    .title {
      color: #fff;
      text-align: center;
      font-size: 24px;
      margin: 0 0 24px;
    }

    .text {
      font-size: 16px;

      :deep(.el-input__inner) {
        color: #fff;
        height: 48px;
        line-height: 48px;

        &::placeholder {
          color: rgba(255, 255, 255, 0.2);
        }
      }
    }

    .btn {
      width: 100%;
    }
  }
}

.captcha {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;

  img {
    cursor: pointer;
    margin-left: 20px;
  }
}

.change-lang {
  position: fixed;
  right: 20px;
  top: 20px;

  :deep(.change-lang) {
    height: 24px;

    &:hover {
      background: none;
    }

    .icon {
      color: #fff;
    }
  }
}
</style>